package sniff;

import java.util.logging.Level;
import java.util.logging.Logger;

import control.SystemControl;
import jpcap.JpcapCaptor;
import jpcap.packet.ARPPacket;
import jpcap.packet.IPPacket;
import jpcap.packet.Packet;
import sniff.diller.ARPPacketDiller;
import sniff.diller.IPPacketDiller;
import sniff.pack.CommonPacket;

public class Sniff implements Runnable{
	private JpcapCaptor jpcap;
	public Sniff(JpcapCaptor jpcap) {
		this.jpcap = jpcap;  
	}

	@Override
	public void run() {
		System.out.println("start run sniff");
		while (true) {
			synchronized (SystemControl.lock) {
				while (SystemControl.suspend) {
					System.out.println("\nsuspend sniff\n");
                    try {
                    	SystemControl.lock.wait();
                    } catch (InterruptedException ex) {
                        Logger.getLogger(Sniff.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }
				Packet pack = jpcap.getPacket();
				CommonPacket comPack;
				if (pack instanceof IPPacket) {
					comPack = IPPacketDiller.dill(pack);
					SystemControl.appendPacket(comPack);
				} else if (pack instanceof ARPPacket) {
					comPack = ARPPacketDiller.dill(pack);
					SystemControl.appendPacket(comPack);
				} else {
					comPack = null;
					System.out.println("Other Packet; In Sniff");
				}
			}
		}
	}

	public JpcapCaptor getJpcap() {
		return jpcap;
	}

	public void setJpcap(JpcapCaptor jpcap) {
		this.jpcap = jpcap;
	}
	
}
